import WS_ADDRESS from '../config/index'
import { useStore } from 'vuex'
const store = useStore()

function useWebScoket(handleMessage, uid) {
    const ws = new WebSocket(WS_ADDRESS + uid)

    const init = ()=> {
        bindEvent()
    }



    // 绑定监听事件和回调函数,一般情况都是把handleMessage当作参数写入useWebScoket的形参中,供在其他组件使用。
    // 以下几个函数都是内部使用
    // handleOpen
    // handleClose
    // handleError
    function bindEvent() {
        ws.addEventListener('open',handleOpen, false)
        ws.addEventListener('close',handleClose, false)
        ws.addEventListener('error',handleError, false)
        ws.addEventListener('message',handleMessage, false)
    }

    function handleOpen(e) {
        console.log('wbsocket open:',e);
        // todo websocket给服务器定时发送心跳
        setInterval(() => {
            // 发送心跳包
            const heart = {
                SenderId:uid,
                ReceiveId:0,
                Text:"",
                SenderImgUrl:"",
                SenderShortName:"",
                EmojiUrl:"",
                MsgType :5,
            }
            ws.send(JSON.stringify(heart))

        }, 1000 * 60);


    }

    function handleClose(e) {
        console.log('wbsocket close:',e);
        // todo websocket建立重新连接功能
    }

    function handleError(e) {
        console.log('wbsocket error:',e);
        // todo websocket建立重新连接功能
    }
    init()

    return ws
}


export default useWebScoket;